package com.example.springlearn.service.impl;

import com.example.springlearn.bean.UserInfo;
import com.example.springlearn.mapper.UserMapper;
import com.example.springlearn.service.UserService;
import com.example.springlearn.util.StaticParamUtil;
import com.example.springlearn.util.redis.HashUtil;
import com.example.springlearn.util.redis.StringUtil;
import com.example.springlearn.util.redis.ToolsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    HashUtil hashUtil;

    @Resource
    StringUtil stringUtil;

    @Resource
    ToolsUtil toolsUtil;

    @Override
    public void insert(UserInfo userInfo) {

        userInfo.setPassword(Base64.getEncoder().encodeToString(userInfo.getPassword().getBytes(StandardCharsets.UTF_8)));
        userMapper.insert(userInfo);

        if (!toolsUtil.hasKey(StaticParamUtil.USER_NUM)) {
            stringUtil.set(StaticParamUtil.USER_NUM, userMapper.countUsers() + 1);
        } else {
            stringUtil.incr(StaticParamUtil.USER_NUM, 1);
        }

    }

    @Override
    public UserInfo searchUserInfo(UserInfo userInfo) {
        UserInfo user = (UserInfo) hashUtil.hGet(StaticParamUtil.USER_MSG_INFO, userInfo.getUid().toString());
        if (userInfo.equals(user)) {
            log.info("登录数据从 redis 中加载");
            return user;
        } else {
            log.info("登录数据从 mysql 中加载");
            userInfo.setPassword(Base64.getEncoder().encodeToString(userInfo.getPassword().getBytes(StandardCharsets.UTF_8)));
            UserInfo info = userMapper.searchUserInfo(userInfo);
            log.info("{} | {}", userInfo, info);
            hashUtil.hSet(StaticParamUtil.USER_MSG_INFO, userInfo.getUid().toString(), info);
            return info;
        }

    }

    @Override
    public Integer countUsers() {
        boolean hasKey = toolsUtil.hasKey(StaticParamUtil.USER_NUM);

        if (hasKey) {
            return (Integer) stringUtil.get(StaticParamUtil.USER_NUM);
        } else {
            Integer integer = userMapper.countUsers();
            stringUtil.set(StaticParamUtil.USER_NUM, integer);
            return integer;
        }

    }
}
